package com.flying.rp.chapter2.comp;

import com.flying.rp.chapter2.model.Temperature;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


@Component
public class TemperatureSensor {
    private final ApplicationEventPublisher publisher;
    private final Random rnd;
    private final ScheduledExecutorService executor;

    public TemperatureSensor(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
        this.rnd = new Random();
        this.executor = Executors.newSingleThreadScheduledExecutor();
    }

    @PostConstruct
    public void startProcessing() {
        this.executor.schedule(this::probe, 1, TimeUnit.SECONDS);
    }

    private void probe() {
        System.out.println("Thread " + Thread.currentThread().getName());
        double temperature = 16 + rnd.nextGaussian() * 10;
        publisher.publishEvent(new Temperature(temperature));
        executor.schedule(this::probe, rnd.nextInt(5), TimeUnit.SECONDS);
    }
}
